package controller

import (
	"github.com/gin-gonic/gin"
	"go-shop-demo/app/common"
	"go-shop-demo/app/consts"
	"go-shop-demo/app/dto"
	"go-shop-demo/app/service"
	"net/http"
)

func AddOrder(c *gin.Context) {
	order := dto.OrderDto{}
	c.ShouldBindJSON(&order)
	if len(order.UserName) == 0 || len(order.OrderGoods) == 0 {
		c.JSON(401, gin.H{"msg": "用户名未填写或商品未添加"})
		return
	}
	orderid, err := service.AddOrde(order)
	if err != nil {
		c.JSON(401, common.NewResponse(401, err.Error(), nil))
		return
	}
	c.JSON(http.StatusOK, common.GetResponseWithMsg(gin.H{"orderid": orderid}, "订单完成"))
	return

}

func DeleteOrder(c *gin.Context) {
	req := common.DeleteReq{}
	err := c.ShouldBindJSON(&req)
	common.CheckErr(err, consts.ClientError, "")
	service.DeleteOrder(req.ID)
	c.JSON(http.StatusOK, common.GetNilResponse())
	return
}

func DetailOrder(c *gin.Context) {
	detail := dto.DetailOrderDto{}
	c.ShouldBind(&detail)
	if len(detail.UserName) == 0 {
		c.JSON(401, common.NewResponse(401, "用户名为空", nil))
		return
	}
	if detail.Status != 0 && detail.Status != 1 {
		c.JSON(401, common.NewResponse(401, "参数必须为0或1", nil))
		return
	}
	result, err := service.Detail(detail)
	if err != nil {
		c.JSON(401, common.NewResponse(401, err.Error(), nil))
		return
	}
	res := gin.H{"allorder": result, "total": len(result)}
	c.JSON(http.StatusOK, common.GetDataResponse(res))
	return
}

//订单支付
func Payer(c *gin.Context) {
	orderpay := dto.OrderPayDto{}
	c.ShouldBindJSON(&orderpay)
	if len(orderpay.IDS) == 0 {
		c.JSON(401, common.NewResponse(401, "订单id为空", nil))
		return
	}
	err := service.Pay(orderpay.IDS)
	if err != nil {
		c.JSON(401, common.NewResponse(401, err.Error(), nil))
		return
	}
	c.JSON(http.StatusOK, common.GetResponseWithMsg(nil, "支付成功"))
	return

}
